package io.renren.modules.hos.controller;

import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.hos.entity.HosUserEntity;
import io.renren.modules.hos.form.HosLoginForm;
import io.renren.modules.hos.service.HosUserService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hos")
public class HosLoginController extends AbstractHosController {

    @Autowired
    private HosUserService hosUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public R login(@RequestBody HosLoginForm form){
        HosUserEntity user = hosUserService.queryUserByPhone(form.getPhone());

        System.out.println(form.getPassword());
        System.out.println(user);
        if (user == null || !user.getPassword().equals(form.getPassword())){
            return R.error("账号不存在或密码不正确");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getId());
        return r;
    }

    /**
     * 退出
     */
    @PostMapping("/logout")
    public R logout() {
        // sysUserTokenService.logout(getHosUserId());
        sysUserTokenService.logout(ShiroUtils.getHosUserId());
        return R.ok();
    }

    @PostMapping("/login1")
    public R login1(@RequestBody HosLoginForm form){
        SysUserEntity user = sysUserService.queryUserByMobile(form.getPhone());

        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())){
            return R.error("电话号码不存在或密码不正确");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        return r;
    }

    /**
     *  获取用户信息
     * @return
     */
    @RequestMapping("/info")
    public R userInfo(){
        HosUserEntity user = (HosUserEntity) SecurityUtils.getSubject().getPrincipal();
        return R.ok().put("info", user);
    }
}
